package com.dferreira.languagesteach.data_parsers;

import com.dferreira.languagesteach.data_models.Entry;
import com.dferreira.languagesteach.data_models.Subject;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;

public class XMLSubjectParser extends DefaultHandler {
    private final String SUBJECT_TAG = "subject";

    private final ArrayList<Entry> entries;
    private final Subject subject;

    /**
     * Starts the variables to the subject parsing
     */
    public XMLSubjectParser() {
        super();
        entries = new ArrayList<Entry>();
        subject = new Subject();
    }

    /**
     * Called when tag starts
     *
     * @param uri        The Namespace URI, or the empty string if the element has no Namespace URI or if Namespace processing is not being performed.
     * @param localName  The local name (without prefix), or the empty string if Namespace processing is not being performed.
     * @param qName      The qualified name (with prefix), or the empty string if qualified names are not available.
     * @param attributes The attributes attached to the element. If there are no attributes, it shall be an empty Attributes object.
     */
    @Override
    public void startElement(String uri, String localName, String qName,
                             Attributes attributes) {
        String ENTRY_TAG = "entry";
        String SOUND_ATTRIBUTE = "sound";
        String IMAGE_ATTRIBUTE = "img";
        String TEXT_ATTRIBUTE = "text";
        String IMAGES_FOLDER_ATTRIBUTE = "images_folder";

        if (localName.equals(ENTRY_TAG)) {
            Entry entry;
            entry = new Entry();
            entry.setSoundPath(attributes.getValue(SOUND_ATTRIBUTE));
            entry.setImagePath(attributes.getValue(IMAGE_ATTRIBUTE));
            entry.setImageDescription(attributes.getValue(TEXT_ATTRIBUTE));
            entries.add(entry);
        } else if (localName.equals(SUBJECT_TAG)) {
            subject.setImagesFolder(attributes.getValue(IMAGES_FOLDER_ATTRIBUTE));
        }
    }

    /**
     * Called when tag ends
     *
     * @param uri       The Namespace URI, or the empty string if the element has no Namespace URI or if Namespace processing is not being performed.
     * @param localName The local name (without prefix), or the empty string if Namespace processing is not being performed.
     * @param qName     The qualified name (with prefix), or the empty string if qualified names are not available.
     */
    @Override
    public void endElement(String uri, String localName, String qName) {
        if (localName.equals(SUBJECT_TAG)) {
            subject.setEntriesLst(entries);
        }
    }

    /**
     * @return the subject that was parsed
     */
    public Subject getSubject() {
        return subject;
    }

}
